from datetime import datetime
from typing import Optional, List, Literal

import akshare as ak
import pandas as pd
from fastapi import APIRouter, Depends, Query, Body

from config.schemas import BaseResponse
from modules.akshare.dongcai_schema import HistoryResponse, RealtimeResponse, QuoteResponse

router = APIRouter(tags=["数据"], prefix="/trading")


def timestamp_to_date(timestamp: Optional[int]) -> str:
    """将时间戳转换为 YYYYMMDD 格式的日期字符串"""
    if timestamp:
        return datetime.fromtimestamp(timestamp / 1000).strftime("%Y%m%d")
    return datetime.now().strftime("%Y%m%d")


@router.get("/history",
            summary="历史数据",
            response_model=BaseResponse[List[HistoryResponse]])
# depend 无法被文档识别
# async def history_trading(query: HistoryQuery = Depends()):
# 除非是用 post 请求：params: HistoryQuery = Body(...)
async def history_trading(symbol: str = Query(..., title="股票代码"),
                          period: Literal["daily", "weekly", "monthly"] = Query(..., title="周期"),
                          start_date: int = Query(..., title="开始时间戳"),
                          end_date: Optional[int] = Query(None, title="结束时间戳"),
                          adjust: Literal["qfq", "hfq", ""] = Query("qfq", title="复权类型",
                                                                    description="qfq: 前复权, hfq: 后复权, 空字符串: 不复权")):
    start_date = timestamp_to_date(start_date)
    end_date = timestamp_to_date(end_date)

    df = ak.stock_zh_a_hist(
        # **query.model_dump(exclude={"start_time", "end_time"}),
        symbol=symbol,
        period=period,
        adjust=adjust,
        start_date=start_date,
        end_date=end_date,
        timeout=10
    )
    data = df.to_dict(orient="records")
    stock: List[HistoryResponse] = [
        HistoryResponse(
            time=item["日期"],
            symbol=item["股票代码"],
            open=item["开盘"],
            close=item["收盘"],
            high=item["最高"],
            low=item["最低"],
            volume=item["成交量"],
            turnover=item["成交额"],
            amplitude=item["振幅"],
            changePercent=item["涨跌幅"],
            changeAmount=item["涨跌额"],
            turnoverRate=item["换手率"]
        )
        for item in data
    ]

    return BaseResponse.success(stock)


@router.get("/realtime", response_model=BaseResponse[List[RealtimeResponse]], summary="日内分时数据")
async def realtime_trading(symbol: str = Query(..., title="股票代码")):
    """单次返回指定股票最近一个交易日的分时数据, 包含盘前数据"""
    # 获取昨天的日期
    # yesterday = datetime.now() - timedelta(days=2)
    # yesterday_9am = yesterday.replace(hour=9, minute=0, second=0, microsecond=0)
    today_9am = datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)

    start_date = today_9am.strftime("%Y-%m-%d %H:%M:%S")
    end_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    df = ak.stock_zh_a_hist_min_em(
        symbol=symbol,
        start_date=start_date,
        end_date=end_date,
        period='1',
        adjust='',
    )

    data = df.to_dict(orient="records")
    stock: List[RealtimeResponse] = [
        RealtimeResponse(
            time=int(datetime.strptime(item["时间"], "%Y-%m-%d %H:%M:%S").timestamp() * 1000),
            open=item.get("开盘", 0),
            close=item.get("收盘", 0),
            high=item.get("最高", 0),
            low=item.get("最低", 0),
            volume=item.get("成交量", 0),
            turnover=item.get("成交额", 0),
            avg_price=item.get("均价", 0),
        )
        for item in data
    ]
    return BaseResponse.success(stock)


@router.get("/quote", response_model=BaseResponse[List[QuoteResponse]], summary="行情报价")
async def quote_trading(symbol: str = Query(..., title="股票代码")):
    """
    获取指定股票的实时行情报价数据

    - **symbol**: 股票代码 (如: 000001 平安银行)
    - 返回: 包含买卖五档盘口和实时交易数据
    """
    df = ak.stock_bid_ask_em(symbol=symbol)
    data = df.to_dict(orient="records")
    # 转换为 {item: value} 字典
    print(data)
    quotes = []
    for item in data:
        # 先构建一个临时字典，将item/value结构转换为字段名/值结构
        temp_dict = {item['item']: item['value'] for item in data}

        quote = QuoteResponse(
            sell_5=temp_dict.get("sell_5", 0),
            sell_5_vol=temp_dict.get("sell_5_vol", 0),
            sell_4=temp_dict.get("sell_4", 0),
            sell_4_vol=temp_dict.get("sell_4_vol", 0),
            sell_3=temp_dict.get("sell_3", 0),
            sell_3_vol=temp_dict.get("sell_3_vol", 0),
            sell_2=temp_dict.get("sell_2", 0),
            sell_2_vol=temp_dict.get("sell_2_vol", 0),
            sell_1=temp_dict.get("sell_1", 0),
            sell_1_vol=temp_dict.get("sell_1_vol", 0),

            buy_1=temp_dict.get("buy_1", 0),
            buy_1_vol=temp_dict.get("buy_1_vol", 0),
            buy_2=temp_dict.get("buy_2", 0),
            buy_2_vol=temp_dict.get("buy_2_vol", 0),
            buy_3=temp_dict.get("buy_3", 0),
            buy_3_vol=temp_dict.get("buy_3_vol", 0),
            buy_4=temp_dict.get("buy_4", 0),
            buy_4_vol=temp_dict.get("buy_4_vol", 0),
            buy_5=temp_dict.get("buy_5", 0),
            buy_5_vol=temp_dict.get("buy_5_vol", 0),

            last_price=temp_dict.get("最新", 0),
            avg_price=temp_dict.get("均价", 0),
            change_percent=temp_dict.get("涨幅", 0),
            change_amount=temp_dict.get("涨跌", 0),
            volume=temp_dict.get("总手", 0),
            turnover=temp_dict.get("金额", 0),
            turnover_rate=temp_dict.get("换手", 0),
            volume_ratio=temp_dict.get("量比", 0),

            high=temp_dict.get("最高", 0),
            low=temp_dict.get("最低", 0),
            open=temp_dict.get("今开", 0),
            prev_close=temp_dict.get("昨收", 0),
            upper_limit=temp_dict.get("涨停", 0),
            lower_limit=temp_dict.get("跌停", 0),

            bid_volume=temp_dict.get("外盘", 0),
            ask_volume=temp_dict.get("内盘", 0),

            timestamp=int(datetime.now().timestamp() * 1000)  # 使用当前时间戳
        )
        quotes.append(quote)

    return BaseResponse.success(quotes)

# 文档地址：https://akshare.akfamily.xyz/data/stock/stock.html#id12
